﻿using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Windows.Forms;
using System.Globalization;
using System.Linq;

namespace UtfprLibrary.Windows.Forms.ComponentModel {
    /// <summary>
    /// TODO
    /// </summary>
    public class UtfprValidatableControlConverter : CollectionConverter {
        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="context"></param>
        /// <param name="destType"></param>
        /// <returns></returns>
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destType) {
            if (destType == typeof(InstanceDescriptor)) {
                return true;
            }

            return base.CanConvertTo(context, destType);
        }

        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="context"></param>
        /// <param name="info"></param>
        /// <param name="value"></param>
        /// <param name="destType"></param>
        /// <returns></returns>
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo info, object value, Type destType) {
            if (destType == typeof(InstanceDescriptor)) {
                UtfprValidatableControl item = (UtfprValidatableControl)value;
                ConstructorInfo ctor =
                  typeof(UtfprValidatableControl).GetConstructor(
                  new Type[] { typeof(Control), typeof(string) });

                object obj = new InstanceDescriptor(ctor,
                   new object[] { item.Control, item.ErrorMessage });

                return obj;
            }

            return base.ConvertTo(context, info, value, destType);
        }
    }
}
